/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Channel.js
 * @path:   js-src/album/
 * @author: jiegang@qiyi.com
 * @date:   2013-01-07
 */
qui(
    function (require, exports, module) {
        Channel.Edit = function (options) {
            this.dao = Channel.Dao;
            this.config = Channel.Config;
            this.task = Channel.Task;
            this.options = options || {};
        };

        Com.inherits(Channel.Edit, {}).extend({
            run: function () {
                var self = this;
                var taskArr = [];
//                taskArr.push(self.task.getConfigType(self.dao.cfgName.liveChannelType));
//                taskArr.push(self.task.getConfigType(self.dao.cfgName.LiveType));
//                taskArr.push(self.task.getConfigType("InterruptType"));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    //  console.log("channel edit init over");
                    self.init();
                })
                EpgWeb.ajaxQueue.startLoad();
            },
            init: function () {
                var self = this;
                var $container = self.options.$container;
                Channel.Util.bindDatetimepicker([$container.find('input[name="tempStartTime"]'),
                    $container.find('input[name="tempEndTime"]'),
                    $container.find('input[name="paidStartTime"]'),
                    $container.find('input[name="paidEndTime"]')
                ]);

                this.bindEditEvent($container);
                //描述字数限制
                Ancestor.Util.limitWordCount($('.channel-edit-form textarea[name="description"]'), 300);
                Ancestor.Util.qitanSuggest($('input.qitanSuggest'));
                Ancestor.Util.alternatePlayCollectionSuggest($('input.alternatePlayCollectionSuggest'));
            },
            // 绑定频道编辑事件
            bindEditEvent: function ($container) {
                // 节目单代码验证方法
                jQuery.validator.addMethod("alphaNumber", function (value, element) {

                        var re = new RegExp("^([a-z]|[A-Z])+[0-9]*[\-]*[0-9]*([a-z]|[A-Z])*$");
                        return re.test(value);
                    }, ""
                );
                this._editBindEvent();
                this._liveTypeLinkage();
                Channel.Util._initEditData($container);
                Channel.Util._initEditEvent();
            },
            _editBindEvent: function () {
                var self = this;
                var $container = self.options.$container;
                var $submit = $container.find('#Submit');
                var id = Channel.Util._getChannelId('id');

                if (id == null)
                    document.title = "频道新增";
                else
                    document.title = "频道修改";

                var validator = Channel.Util.getValidator($container, Channel.Config.EDIT);
                $submit.on('click', function () {
                    // 提交前验证
                    if (!validator.form())
                        return;
                    if ($.trim($("#ctn-tps").text()) != "") {
                        if (id != null && Stream.Config.ctn == $('input[name="carousel_table_no"]').val()) {
                        } else {
                            $(document).tips({
                                content: "轮播台台号重复！",
                                type: "error"
                            });
                            return;
                        }
                    }
                    var data = Channel.Util.getParam($container);
                    if (data.liveType === '3') {
                        if (!Channel.Util.checkAutomationType(data['automation'])) {
                            $(document).tips({  content: "请选择正确的节目单类型。", type: "error" });
                            return;
                        }
                        if ($('input[name="alternatePlayCollection"]').val().length == 0) {
                            $(document).tips({  content: "请添加备播库节目", type: "error" });
                        }
                        if ($('input[name="tag"]').val().length == 0) {
                            $(document).tips({  content: "请设置大小写分类", type: "error" });
                        }
                    }
                    if (!Channel.Util.checkSubjectUrl(data)) {
                        $(document).tips({
                            content: "专题页url格式错误,请修改后保存.",
                            type: "error"
                        });
                        return;
                    }

                    if (!Channel.Util.checkMaxPlaybackPeriod(data)) {
                        $(document).tips({
                            content: "最大回看时间不允许大于48小时,请修改后保存.",
                            type: "error"
                        });
                        return;
                    }

                    $(this).attr("disabled", "disabled");

                    $(document).tips({
                        content: "页面提交中",
                        type: "loading"
                    });

                    Channel.Config.SLICE_DELAY_CHECK.data = data;
                    // 检验压流延时的修改
                    Channel.Util.checkSliceDelay();
                    return;
                });
                Channel.Util.imageCrop($('#AlbumEditScreenCorp'));
                $('input[name="isMemeberFree"]').on('click.radio', function () {
                    if ($('input[name="isMemeberFree"]:checked').val() == 0) {
                        $('#isMemeberFree').show();
                    } else {
                        $('#isMemeberFree').hide();
                    }
                });
                $('input[name="formal"]').on('click.radio', function () {
                    var categoryWarn = $('#category-warn');
                    var tagshow = $('span.tagshow');
                    var tag = $('input[name="tag"]');
                    if ($('input[name="formal"]:checked').val() == 0) {
                        tagshow.attr("record", tagshow.text());
                        tagshow.attr("recordTag", tag.val());
                        tagshow.text("正在直播_临时直播");
                        tag.val("200003919_200978719");
                        categoryWarn.css("display", "inline-block");
                    } else {
                        tagshow.text(tagshow.attr("record"));
                        tag.val(tagshow.attr("recordTag"));
                        categoryWarn.css("display", "none");
                    }
                });
            },
            _liveTypeLinkage: function (id) {
                $('select[name=type]').bind("change", function (e) {
                    if ($(this).val() == 5 || $(this).val() == 11) {
                        Channel.Dao.carouselTableNo({
                            carousel_table_no: $(".channel-edit-form").find("input[name=carousel_table_no]").val(),
                            type: $(this).val(),
                            channelId: Ancestor.Util.getUrlId('id')
                        }, function (json) {
                            if (json.code == 'A00000') {
                                $("#ctn-tps").text(json.msg).show();
                            } else {
                                $("#ctn-tps").text("").hide();
                            }
                        });
                    }
                });
                $('select[name="liveType"]').bind("change", function (event) {
                    var html = '';
                    if ($(this).val() == 1) {
                        $.each(Channel.Config.NormalChannel, function (i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });
                        $('#ucode').show();
                        $('#ucode').find('[name="universalCode"]').removeAttr('disabled');
                        $("#alternatePlayCollectionIdsGroup").hide();
                        $("#carouselTableNo").html("").hide();
                        $("#sDelay").hide();
                        $("#isTest").hide();
                        $("#subjectUrlGroup").hide();
                        $("#automationBlock").hide();
                    } else if ($(this).val() == 2) {
                        $.each(Channel.Config.TempChannel, function (i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });

                        $('#ucode').hide();
                        $('#ucode').find('[name="universalCode"]').attr('disabled', 'disabled');
                        $("#alternatePlayCollectionIdsGroup").hide();
                        $("#carouselTableNo").html("").hide();
                        $("#sDelay").show();
                        $("#isTest").show();
                        $("#subjectUrlGroup").show();
                        $("#automationBlock").hide();
                        $("#category-control-div").hide();

                    } else if ($(this).val() == 3) {
                        $.each(Channel.Config.Carousel, function (i, n) {
                            html += '<option value="' + i + '">' + n + '</option>';
                        });
                        $('#ucode').hide();
                        $('#ucode').find('[name="universalCode"]').attr('disabled', 'disabled');
                        $("#alternatePlayCollectionIdsGroup").show(); // 备播库显示
                        Channel.Util._writeCarouselTableNoHtml("");
                        $("#sDelay").hide();
                        $("#isTest").hide();
                        $("#subjectUrlGroup").hide();
                        $("#automationBlock").show();
                        $("#category-control-div").show();
                    }
                    $('select[name="type"]').html(html);
                });
            }
        })

    }
);